import React from 'react';
import styled from 'styled-components';
import { useParams, useHistory } from 'react-router-dom';
import { useTags } from 'hooks/useTags';
import { Layout } from 'components/Layout';
import { Icon } from 'components/Icon';
import { Button } from 'components/Button';
import { Input } from 'components/Input';
import { Center } from 'components/Center';
import { Space } from 'components/Space';

type Params = {
  id: string;
};

const Topbar = styled.header`
  display: flex;
  justify-content: space-between;
  align-items: center;
  line-height: 20px;
  padding: 14px;
  background: #fff;
`;

const InputWrapper = styled.div`
  background: #fff;
  padding: 0 16px;
  margin-top: 8px;
`;

export const Tag: React.FC = () => {
  const { findTag, updateTag, deleteTag } = useTags();
  const { id: idString } = useParams<Params>();
  const tag = findTag(parseInt(idString));
  const history = useHistory();
  const onClickBack = () => {
    history.goBack();
  };
  const tagContent = (tag: { id: number; name: string }) => (
    <div>
      <InputWrapper>
        <Input
          label="标签名"
          type="text"
          placeholder="标签名"
          value={tag.name}
          onChange={e => {
            updateTag(tag.id, { name: e.target.value });
          }}
        />
      </InputWrapper>
      <Center>
        <Space />
        <Space />
        <Button
          onClick={() => {
            deleteTag(tag.id);
            history.goBack();
          }}
        >
          删除标签
        </Button>
        <Space />
        <Space />
      </Center>
    </div>
  );

  return (
    <Layout>
      <Topbar>
        <Icon name="left" onClick={onClickBack} />
        <span>编辑标签</span>
        <Icon />
      </Topbar>
      {tag ? tagContent(tag) : ''}
    </Layout>
  );
};
